package com.southwind.controller;

import com.southwind.entity.Admin;
import com.southwind.entity.User;
import com.southwind.feign.AccountFeign;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;

/**
 * @program: aspringclouddemo
 * @description:
 * @author: xzf
 * @create: 2021-12-10 10:45
 **/
@Controller
@RequestMapping("/account")
public class AccountClientHandler {
    @Resource
    AccountFeign accountFeign;

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("type") String type, HttpSession session) {
        Object obj = accountFeign.login(username, password, type);
        LinkedHashMap<String, Object> hashMap = (LinkedHashMap) obj;
        String result = "";
        if (obj == null) {
            result = "login";
        } else {
            switch (type) {
                case "user":
                    User user = new User();
                    user.setId((Integer) hashMap.get("id"));
                    user.setNickname((String) hashMap.get("nickname"));
                    session.setAttribute("user", user);
                    result = "index";
                    break;
                case "admin":
                    Admin admin = new Admin();
                    admin.setId((Integer) hashMap.get("id"));
                    admin.setUsername((String) hashMap.get("username"));
                    session.setAttribute("admin", admin);
                    result = "main";
                    break;
            }
        }
        return result;
    }

    //    用户点击了退出登录的路由
//    需要摧毁session
    @GetMapping("/logout")
    public String logout(HttpSession session) {
//        摧毁session
        session.invalidate();
//        跳转到登录页面
        return "redirect:/login.html";
    }
}
